import kotlin.reflect.KProperty

/**
 * @author aidenquan
 *         Created by junlintianxia on 2021/07/05.
 */

class Delegate(initValue: String = "") {
    private var localValue: String = initValue

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "getValue ${property.name}: $thisRef $localValue"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("value=$value")
        localValue = value
        println("localValue=$localValue")
    }
}

class DelegateTest {
    private var s1: String by Delegate()
    fun test1() {
        println(s1)
        s1 = "改变后的值"
        println(s1)
    }

    fun test2() {
        var s2: String by Delegate("默认值2")
        println(s2)
    }

    companion object {
        private var s3: String by Delegate()
        private val delegateTest: DelegateTest by lazy {
            DelegateTest()
        }
        fun test3() {
            println(s3)
        }

        fun test4() {
            var s4: String by Delegate("默认值4")
            println(s4)
        }
    }
}

fun main(args: Array<String>) {
    val test = DelegateTest()
    test.test1()
    test.test2()
    DelegateTest.test3()
    DelegateTest.test4()
}
